import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {request} from "../../utils/index.jsx";

const Index = () => {
    const [username, setUsername] = useState('');
    const [role, setRole] = useState('');
    const [error, setError] = useState('');


    useEffect(() => {
        const fetchDashboard = async () => {
            try {
                const response = await request.get('/dashboard');
                setUsername(response.data.username || '未知用户');
                setRole(response.data.role || '未知角色');
                console.log(response.data)
            } catch (error) {
                console.error('Fetch dashboard error:', error);
                if (error.response) {
                    setError(error.response.data.error);
                    console.log(error.response)
                } else {
                    setError('请求出错');
                }
            }
        };

        fetchDashboard();
    }, []);

    const handleLogout = () => {
        localStorage.removeItem('token');
        window.location.href = '/login';
    };

    return (
        <div>
            <h1>欢迎来到仪表盘</h1>
            {error ? (
                <p style={{ color: 'red' }}>{error}</p>
            ) : (
                <p>欢迎，{username}！你是 {role}。</p>
            )}
            <button onClick={handleLogout}>退出登录</button>
        </div>
    );
};

export default Index;